#pragma once

#include <iostream>
#include <unordered_map>
#include <fstream>
#include <string>
#include "Log.hpp"

namespace dict_ns
{
    const std::string DefaultFilepath = "./Dict.txt";
    const std::string sep = ": ";
    class Dict
    {
    private:
        bool Load()
        {
            std::ifstream in(_dict_conf_filepath);//从文件中读取数据

            // 文件打开失败
            if (!in.is_open())
            {
                LOG(FATAL, "open %s error\n", _dict_conf_filepath);
                return false;
            }

            std::string line;// 一行
            // 文件打开成功
            while (std::getline(in, line))
            {
                //该行无效
                if (line.empty())
                    continue;

                auto pos = line.find(sep); // 找到分隔符

                // 没找到分隔符，说明该行无效
                if (pos == std::string::npos)
                    continue;

                std::string word = line.substr(0, pos); // 单词
                if (word.empty())
                    continue; // 单词是空串，单词无效

                std::string meaning = line.substr(pos + sep.size()); // 含义
                if (meaning.empty())
                    continue; // 含义是空串，无效

                LOG(DEBUG,"load info, %s: %s\n",word.c_str(),meaning.c_str());
                _dict.insert(std::make_pair(word, meaning));
            }

            in.close(); // 关闭文件
            LOG(DEBUG, "load %s success\n", _dict_conf_filepath);
            return true;
        }

    public:
        Dict(const std::string &path = DefaultFilepath)
            : _dict_conf_filepath(path)
        {
            Load(); // 初始化字典
        }

        std::string Translate(const std::string &word,bool &ok)
        {
            if(_dict.find(word)==_dict.end())
            {
                ok=false;
                return "未找到";
            }
            return _dict[word];
        }
        ~Dict()
        {
        }

    private:
        std::unordered_map<std::string, std::string> _dict; // 字典
        std::string _dict_conf_filepath;                    // 字典文件的路径
    };
}